package boun.center;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Pair;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class PreferencesActivity extends Activity {

	@Override
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		setContentView(R.layout.preferences);
		try {
			Pair<String,String> credentials = RegistrationActivity.readFrom(openFileInput("preferences"));
			EditText idText = (EditText) findViewById(R.id.SchoolIDPref);
			idText.setText(credentials.first);
			EditText pwText = (EditText) findViewById(R.id.PasswordPref);
			pwText.setText(credentials.second);
		} catch (FileNotFoundException e1) {
		} catch (IOException e1) {
		}
		
		Button b = (Button) findViewById(R.id.PrefButton);
		b.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				String id = ((EditText)findViewById(R.id.SchoolIDPref)).getText().toString();
				String pw = ((EditText)findViewById(R.id.PasswordPref)).getText().toString();
				try {
					storeData(id,pw);
					Toast.makeText(getApplicationContext(), "Saved!", Toast.LENGTH_SHORT).show();
				} catch (IOException e) {
					Toast.makeText(getApplicationContext(), "Something went wrong!", Toast.LENGTH_LONG).show();
				}
			}
			
		});
	}

	protected void storeData(String id, String pw) throws IOException {
		String buf = id+"\n"+pw+"\n";
		FileOutputStream fos = openFileOutput("preferences",Context.MODE_PRIVATE);
		fos.write(buf.getBytes());
		fos.close();
	}
}
